﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SRF.Data.SQLParser
{
    /// <summary>
    /// 用velocity方式解析语句
    /// </summary>
    class VelocitySQLParser : ISQLParser
    {
        NVelocity.App.VelocityEngine engine;

        public VelocitySQLParser()
        {
            engine = new NVelocity.App.VelocityEngine();
            engine.Init();
        }

        public string Parse(string sql, IDictionary<string, object> parameters, char parameterToken)
        {
            NVelocity.VelocityContext content = new NVelocity.VelocityContext();

            content.Put("util", Util.Get());
            foreach (KeyValuePair<string, object> kv in parameters)
            {
                content.Put(kv.Key, kv.Value);
            }
            System.IO.StringWriter writer = new System.IO.StringWriter();
            engine.Evaluate(content, writer, "VelocitySQLParser", sql);

            return writer.ToString();
        }

        static VelocitySQLParser _instance;

        public static ISQLParser Get()
        {
            if (_instance == null)
            {
                _instance = new VelocitySQLParser();
            }
            return _instance;
        }

        #region 

        /// <summary>
        /// 扩展函数
        /// </summary>
        public class Util
        {
            /// <summary>
            /// 是否为空或字符串是否为空
            /// </summary>
            /// <param name="obj"></param>
            /// <returns></returns>
            public bool IsNullOrEmpty(object obj)
            {
                if (obj == null)
                    return true;
                else
                    return string.IsNullOrEmpty(obj.ToString());
            }

            static Util _instance;

            /// <summary>
            /// 获取Util实例
            /// 单例模式
            /// </summary>
            /// <returns></returns>
            public static Util Get()
            {
                if (_instance == null)
                    _instance = new Util();
                return _instance;
            }
        }

        #endregion

        public string Parse(string sql, Func<string, object> getParameterValue, char parameterToken)
        {
            throw new NotImplementedException();
        }
    }
}